package cn.uniquesoft.controller;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.service.ICompanyService;
import cn.uniquesoft.service.ISearchService;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.DateUtil;
import cn.uniquesoft.util.FileUpUtil;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.CompanyVO;
import cn.uniquesoft.vo.SearchVO;
import cn.uniquesoft.vo.UserVO;
import cn.uniquesoft.vo.base.BaseVO;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

@Controller
@RequestMapping(value="/company")
@SuppressWarnings("unused")
public class CompanyController extends BaseController<CompanyVO> {
    @Autowired
    private ISearchService searchService;
    private ICompanyService iCompanyService;
    private static String fileExts = ".xls,.xlsx";
    public CompanyController(ICompanyService iCompanyService) {
        super();
        this.iCompanyService = iCompanyService;
        this.baseService = iCompanyService;
        this.indexName = "company/index";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public AnswerVO save(CompanyVO item) {
        AnswerVO answerVO = new AnswerVO();
        try {
            MultipartFile file = item.getUpfile();
            if (file.getSize() > 0) {
                String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
                String oldname = file.getOriginalFilename();
                // 算出后缀名
                String ext = oldname.substring(oldname.lastIndexOf("."));
                // 文件名为：问题名称 + image + UUID + 后缀
                String fileName = "company" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
                String filepath = "files" + File.separator + "company" + File.separator;
                String fileFolder = tomurl + filepath;
                File upload = new File(fileFolder);
                if (!upload.exists()) upload.mkdirs();
                File localFile = new File(fileFolder, fileName);

                // 直接写入到后台服务器，简单且快
                file.transferTo(localFile);
                item.setCpicname(oldname);
                item.setCpicpath(fileName);
                item.setCpicsize(FileUpUtil.convertFileSize(file.getSize()));
            }
            this.iCompanyService.save(item);
            int itemId = ((BaseVO) item).getIid();
            if (itemId > 0) {
                SearchVO searchVO = new SearchVO();
                searchVO.setTname("company");
                searchVO.setTid(item.getIid()+"");
                searchVO.setTvalue(item.toString());
                System.out.println(item.toString());
                searchVO.setTtitle(item.getCname());
                searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
                this.searchService.save(searchVO);
                answerVO.setSuccess(true);
                answerVO.setMsg("新增成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("新增失败!");
            }
            answerVO.setData(itemId);
        } catch (Exception e) {
            e.printStackTrace();
            answerVO.setSuccess(false);
            answerVO.setMsg("新增失败," + e.getMessage());
        }
        return answerVO;
    }

    @RequestMapping(value = "/edit")
    @ResponseBody
    public AnswerVO edit(CompanyVO item) {
        AnswerVO answerVO = new AnswerVO();
        try {
            MultipartFile file = item.getUpfile();
            if (file.getSize() > 0) {
                String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
                // 获得上传文件原始名
                String oldname = file.getOriginalFilename();
                // 算出后缀名
                String ext = oldname.substring(oldname.lastIndexOf("."));
                // 文件名为：问题名称 + image + UUID + 后缀
                String fileName = "company" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
                String filepath = "files" + File.separator + "company" + File.separator;
                String fileFolder = tomurl + filepath;
                File upload = new File(fileFolder);
                if (!upload.exists()) upload.mkdirs();
                File localFile = new File(fileFolder, fileName);
                // 直接写入到后台服务器，简单且快
                file.transferTo(localFile);
                item.setCpicname(oldname);
                item.setCpicpath(fileName);
                item.setCpicsize(FileUpUtil.convertFileSize(file.getSize()));
            }
            int result = this.iCompanyService.edit(item);
            if (result > 0) {
                this.searchService.remove(item.getIid()+"", "company");
                SearchVO searchVO = new SearchVO();
                searchVO.setTname("article");
                searchVO.setTid(item.getIid()+"");
                searchVO.setTvalue(item.toString());
                System.out.println(item.toString());
                searchVO.setTtitle(item.getCname());
                searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
                this.searchService.save(searchVO);
                answerVO.setSuccess(true);
                answerVO.setMsg("修改成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("修改失败!");
            }
            answerVO.setData(result);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("修改失败," + e.getMessage());
        }

        return answerVO;
    }

    @RequestMapping(value = "importXls.do")
    @ResponseBody
    public AnswerVO importXls(MultipartFile filedata) {
        AnswerVO answerVO = new AnswerVO();
        if (filedata == null) {
            answerVO.setSuccess(false);
            answerVO.setMsg("文件上传失败！");
            return answerVO;
        }
        // 获得上传文件原始名
        String oldname = filedata.getOriginalFilename();
        // 算出后缀名
        String ext = oldname.substring(oldname.lastIndexOf("."));
        System.out.println("oldname:" + oldname + ",ext:" + ext);
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {

        }
        if (fileExts.indexOf(ext) == -1) {
            answerVO.setSuccess(false);
            answerVO.setMsg("文件上传失败,只能上传" + fileExts + "文件！");
            return answerVO;
        }
        try{
            Workbook wb = Workbook.getWorkbook(filedata.getInputStream());
            Sheet sheet = wb.getSheet(0);
            int rowSize = sheet.getRows();
            System.out.println("rowSize:" + rowSize);
            CompanyVO companyVO = new CompanyVO();
            for (int i = 1; i < rowSize; i++) {
                //企业名
                Cell cell = sheet.getCell(0, i);
                if(cell.getContents().length()>0){
                    companyVO.setCname(cell.getContents());
                    //企业简称
                    cell = sheet.getCell(1, i);
                    companyVO.setCshort(cell.getContents());
                    //企业地址
                    cell = sheet.getCell(2, i);
                    companyVO.setCaddress(cell.getContents());
                    //企业联系人
                    cell = sheet.getCell(3, i);
                    companyVO.setClinkman(cell.getContents());
                    //企业联系电话
                    cell = sheet.getCell(4, i);
                    companyVO.setCphone(cell.getContents());
                    //企业邮箱
                    cell = sheet.getCell(5, i);
                    companyVO.setCemail(cell.getContents());
                    //企业类型
                    cell = sheet.getCell(6, i);
                    companyVO.setCtype(cell.getContents());
                    if(cell.getContents().equals("初创")){
                        companyVO.setItype(1);
                    }else if(cell.getContents().equals("成长")){
                        companyVO.setItype(2);
                    }else{
                        companyVO.setItype(3);
                    }
                    //企业主营业务
                    cell = sheet.getCell(7, i);
                    companyVO.setCmainbusiness(cell.getContents());
                    //企业优势
                    cell = sheet.getCell(8, i);
                    companyVO.setCadvantages(cell.getContents());
                    //企业优势
                    cell = sheet.getCell(9, i);
                    companyVO.setCintroduction(cell.getContents());
                    companyVO.setIcreator(userVO.getIid());
                    companyVO.setCcreator(userVO.getCname());
                    companyVO.setDcreator(new Date());
                    int result = this.iCompanyService.save(companyVO);
                    if (result > 0) {
                        SearchVO searchVO = new SearchVO();
                        searchVO.setTname("company");
                        searchVO.setTid(companyVO.getIid() + "");
                        searchVO.setTvalue(companyVO.toString());
                        System.out.println(companyVO.toString());
                        searchVO.setTtitle(companyVO.getCname());
                        searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
                        this.searchService.save(searchVO);
                        answerVO.setSuccess(true);
                        answerVO.setMsg("新增成功!");
                    } else {
                        answerVO.setSuccess(false);
                        answerVO.setMsg("新增失败!");
                        return answerVO;
                    }
                }
            }
            answerVO.setSuccess(true);
            answerVO.setMsg("导入成功!");
        }catch (Exception e){
            e.printStackTrace();
            answerVO.setSuccess(false);
            answerVO.setMsg("导入失败," + e.getMessage());
        }
        return answerVO;
    }

    @RequestMapping(value = "/removeById")
    @ResponseBody
    @Override
    public AnswerVO removeById(int  iid) {
        AnswerVO answerVO = new AnswerVO();
        try {
            int result = this.baseService.removeById(iid);

            if (result > 0) {
                this.searchService.remove(iid+"", "company");
                answerVO.setSuccess(true);
                answerVO.setMsg("删除成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("删除失败!");
            }
            answerVO.setData(result);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("删除失败," + e.getMessage());
        }

        return answerVO;
    }

    @RequestMapping(value = "/removeByIds")
    @ResponseBody
    @Override
    public AnswerVO removeByIds(String ids) {
        AnswerVO answerVO = new AnswerVO();
        try {
            int result = this.baseService.removeByIds(ids);

            if (result > 0) {
                String[] ss = ids.split(",");
                for(int i=0;i<ss.length;i++){
                    this.searchService.remove(ss[i]+"", "company");
                }
                answerVO.setSuccess(true);
                answerVO.setMsg("删除成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("删除失败!");
            }
            answerVO.setData(result);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("删除失败," + e.getMessage());
        }

        return answerVO;
    }
}
